# -*- coding: utf-8 -*-
from xml.dom import minidom
from os import path, makedirs
from zipfile import ZipFile
#from glob import glob
from time import time
import logging
#from TimeManager import TimeManager
from utils.common import get_file_md5_hash
# When the flute client reveive a zip archive, it calls the FileManager which will unzip and process the widget

ROOT_DIR = path.dirname(__file__)
ZIP_DIR = path.join(ROOT_DIR, 'downloadedfiles')
WIDGETS_DIR_REL = path.join(ROOT_DIR, 'unzipfiles')

log = logging.getLogger("AlicanteHomebox")

class InteractionEvent:
    def __init__(self, channelID=None, serviceID=None, eventPath=None, eventType=None, startTime=None, endTime=None, version=None):
        self.bwork = None
        self.channelID = int(channelID)
        self.serviceID = int(serviceID)
        self.eventType = eventType
        self.version = int(version)
        if startTime:
            self.startTime = time() #startTime
        else:
            self.startTime = time()
        self.endTime = int(endTime) # time() + 100 #endTime
        self.started = False
        self.newInfoFlag = True # New interaction? What the purpose of that?
        self.zipPath = eventPath
        self.md5_hash = get_file_md5_hash(self.zipPath)
        self.zipArchiveSize = path.getsize(self.zipPath)
            
    def __repr__(self):
        return "StartTime: %s, StopTime: %s, EventType: %s" % (self.startTime, self.endTime, self.eventType)
  
    def running(self):
        return self.started
  
    def start(self):
        if self.newInfoFlag:
            self.newInfoFlag = False
            self.started = True
    
    def stop(self):
        self.started = False
    
    
class FileManager:
    def __init__(self):
        pass
  
    def findXmlFile(self, directory):
        pass
        #xmlfile = glob( path.join(directory, '*.xml') )
        #if len(xmlfile) > 1:
            #raise IOError("More than one xml file in: %s" % directory)
        #else:
            #return xmlfile[0]
    
    
    def unzipXml(self, filename):
        # We just need the configuration file
        zip = ZipFile(filename, 'r')
        zip_folder = path.join(WIDGETS_DIR_REL, path.split(path.splitext(zip.filename)[0])[-1])
        if not path.isdir(zip_folder):
            makedirs(zip_folder)
        
        xmlFiles = filter(lambda x: x.endswith(".xml") and x.startswith("SDI"), zip.namelist())
        if len(xmlFiles) != 1:
            raise IOError("The zip archive should contain one xml file")
        else:
            xmlFile = xmlFiles[0]
            root, name = path.split(xmlFile)
            directory = path.normpath(path.join(zip_folder, root))
            if not path.isdir(directory):
                makedirs(directory)
            file(path.join(zip_folder, name), 'wb').write(zip.read(xmlFile))
            return path.join(zip_folder, name)
          
    
    def xmlParsing(self, filename, zipfilename):
        fxml = open(filename)
        xmldom = minidom.parse(fxml)
        fxml.close()
        
        serviceDescription = xmldom.firstChild
        
        newEvent = InteractionEvent(
            serviceID=serviceDescription.getAttribute("ID"),
            eventType=serviceDescription.getAttribute("ServiceType"),
            startTime=serviceDescription.getAttribute("StartTime"),
            endTime=serviceDescription.getAttribute("EndTime"),
            channelID=serviceDescription.getAttribute("ChannelRef"),
            version=serviceDescription.getAttribute("Version"),
            eventPath=zipfilename
            )
        
        return newEvent
        
        #forecasts.append({
            #'date': node.getAttribute('date'),
            #'low': node.getAttribute('low'),
            #'high': node.getAttribute('high'),
            #'condition': node.getAttribute('text')
        #})
      
    def mappingFileParsing(self, filename):
        fxml = open(filename)
        xmldom = minidom.parse(fxml)
        fxml.close()
        
        serviceDescription = xmldom.firstChild
        
        mappingInfos = {}
        
        for channel in serviceDescription.childNodes:
            if channel.nodeName == "Channel":
                temp = mappingInfos[ int(channel.getAttribute("CHANNELID")) ] = {}
                temp["FLUTEIP"] = channel.getAttribute("FLUTEIP")
                temp["FLUTEPORT"] = int(channel.getAttribute("FLUTEPORT"))
                temp["AVIP"] = channel.getAttribute("AVIP")
                temp["AVPORT"] = int(channel.getAttribute("AVPORT"))
        
        return mappingInfos
        
        
        def removeFile(self):
            pass
        
        def removeDirectory(self):
            pass
      
      
    
    
    

